package com.king.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author king
 * @date 2020/9/6 22:29
 */
@Slf4j
@Service
public class PaymentService {

    /**
     * 正常访问
     *
     * @param id id
     * @return 结果
     */
    public String paymentInfo_OK(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_OK, id: " + id;
    }

    /**
     * 异常访问
     *  HystrixCommand
     *      fallbackMethod 出错调用补救方法
     *      commandProperties
     *          HystrixProperty 响应峰值设置, 超过则调用补救方法
     * @param id id
     * @return 结果
     */
    public String paymentInfo_Timeout(Integer id) {
        int time = 5;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_Timeout, id: " + id + "耗时（秒）：" + time;
    }

    /**
     * 超时补救
     *  HystrixCommand
     *      fallbackMethod 出错调用补救方法
     *      commandProperties
     *          HystrixProperty 响应峰值设置, 超过则调用补救方法
     * @param id id
     * @return 结果
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfo_Timeout3(Integer id) {
        int time = 5;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_Timeout, id: " + id + "耗时（秒）：" + time;
    }

    /**
     * 正常延时
     *  HystrixCommand
     *      fallbackMethod 出错调用补救方法
     *      commandProperties
     *          HystrixProperty 响应峰值设置, 超过则调用补救方法
     * @param id id
     * @return 结果
     */
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public String paymentInfo_Timeout5(Integer id) {
        int time = 3;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + " paymentInfo_Timeout, id: " + id + "耗时（秒）：" + time;
    }

    public String paymentInfo_TimeoutHandler(Integer id){
        return "paymentInfo_TimeoutHandler";
    }


    // =====服务熔断

    /**
     * 熔断测试
     * @param id 测试
     * @return 返回结果
     */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),  // 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),   // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")    // 失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(Integer id){
        if(id < 0){
            log.debug("ID不能为负数");
            throw new RuntimeException("id不能为负数");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "调用成功, 流水号: " + serialNumber;
    }

    /**
     * 熔断回调
     * @param id 参数
     * @return 返回值
     */
    public String paymentCircuitBreakerFallback(Integer id){
        return "id不能为负数";
    }
}
